﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Configuration;
using MarginTrading.Entity;
using MarginTrading.Services;
using System.Globalization;

namespace MarginTrading.Forms
{
    public partial class AgentDataLoading : Form
    {
        String TrHdrFile = "Headers\\ats2_ttr.hdr";
        //String CDSTranHdrFile = "D:\\CDS_Tran.hdr";
        String TrsumHdr = "Headers\\trsum.hdr";
        String BROKER_CODE = "";
        String AgentCode = "";
        String CDSTranHdrFile = "Headers\\CDS_Tran.hdr";

        public AgentDataLoading()
        {
            InitializeComponent();

            try
            {
                Config AgentCodeConfig = ConfigServices.GetConfigByName("Agent Code");
                AgentCode = AgentCodeConfig.Value;
                

            }
            catch (System.Exception ex)
            {
                MessageBox.Show("Database Error occurred.", "Error");
               
            }


        }

        private void groupBox1_Enter(object sender, EventArgs e)
        {

        }

        private void TrDataBwsBtn_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog1 = new OpenFileDialog();

            //openFileDialog1.InitialDirectory = "D:\\";
            openFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
            openFileDialog1.FilterIndex = 2;
            openFileDialog1.RestoreDirectory = true;

            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    AtsDataTxtBox.Text = openFileDialog1.FileName;
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
                }
            }
        }

        private void TrsumBwsBtn_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog1 = new OpenFileDialog();

            //openFileDialog1.InitialDirectory = "D:\\";
            openFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
            openFileDialog1.FilterIndex = 2;
            openFileDialog1.RestoreDirectory = true;

            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    TrsumFile.Text = openFileDialog1.FileName;
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
                }
            }
        }



        private void PortDataBrwsBtn_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog1 = new OpenFileDialog();

            //openFileDialog1.InitialDirectory = "D:\\";
            openFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
            openFileDialog1.FilterIndex = 2;
            openFileDialog1.RestoreDirectory = true;

            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    PortFile.Text = openFileDialog1.FileName;
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
                }
            }
        }

        private void TrCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private bool PreValidation()
        {
            DialogResult result = DialogResult.Yes;
            if (!CDSTranServices.IsProcessed(HolidayServices.GetPreMktDay(TrDate.Value.Date), "Trades"))
            {
                result = MessageBox.Show(HolidayServices.GetPreMktDay(TrDate.Value.Date).ToShortDateString() +
                    " transactions are not available.\nDo you want to proceed? ", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
            }
            if (result == DialogResult.No)
                return false;
            if (!CDSTranServices.IsProcessed(HolidayServices.GetPreMktDay(TrDate.Value.Date), "CDSTran"))
            {
                result = MessageBox.Show(HolidayServices.GetPreMktDay(TrDate.Value.Date).ToShortDateString() +
                    " CDS uploads are not available.\nDo you want to proceed? ", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
            }
            if (result == DialogResult.No)
                return false;

            return true;

        }


        private void TrUpload_Click(object sender, EventArgs e)
        {

            if (!PreValidation())
                return;

            if (AtsDataTxtBox.Text == "")
            {
                MessageBox.Show("Select a trade file.", "Message");
                return;
            }
            if (TrsumFile.Text == "")
            {
                MessageBox.Show("Select the trsum file.", "Message");
                return;
            }

            ReadTradeHdrFile(TrHdrFile, 6);
            ReadTradeFile();

            progressBar1.Value = 0;
            ReadTradeHdrFile(TrsumHdr, 3);
            ReadTrsumFile();
            LogBox.AppendText("Data loading - ended\n");
            progressBar1.Value = 0;
        }



        public void ProBar_()
        {
            progressBar1.Increment(1);

            if (progressBar1.Value == progressBar1.Maximum)
            {
                //MessageBox.Show("File Loading Done !");                            
            }
        }

        private void portRadioBtn_CheckedChanged(object sender, EventArgs e)
        {
            groupBox1.Enabled = false;
            groupBox2.Enabled = true;
        }

        private void TrRadioBtn_CheckedChanged(object sender, EventArgs e)
        {
            groupBox2.Enabled = false;
            groupBox1.Enabled = true;
        }

        private void AgentDataLoading_Load(object sender, EventArgs e)
        {
            TrRadioBtn.Select();
            groupBox2.Enabled = false;
            BtnEnable();
        }

        private int NoOfBrockers = 4;
        private int PageNo = 1;

        private void NextBtn_Click(object sender, EventArgs e)
        {
            PageNo++;
            //PageComment.Text = PageNo.ToString();
            BtnEnable();


        }

        private void PrevBtn_Click(object sender, EventArgs e)
        {
            PageNo--;
            //PageComment.Text = PageNo.ToString();
            BtnEnable();
        }

        private void BtnEnable()
        {
            PrevBtn.Enabled = true;
            NextBtn.Enabled = true;
            TrRadioBtn.Enabled = false;
            portRadioBtn.Enabled = false;

            if (PageNo == 1)
            {
                PrevBtn.Enabled = false;
                TrRadioBtn.Enabled = true;
                portRadioBtn.Enabled = true;
            }
            if (NoOfBrockers == PageNo)
            {
                NextBtn.Enabled = false;
            }
            PageComment.Text = "Step " + PageNo.ToString() + " of " + NoOfBrockers.ToString();
        }



        /////////////////////////////Duplicate///////////////////////////////////////
       

        int LineWidth = 0;
        static Dictionary<String, int> mapOffset = new Dictionary<String, int>();
        static Dictionary<String, int> mapSize = new Dictionary<String, int>();



        public void ReadTradeHdrFile(String FilePath, int StartRow)
        {
            try
            {
                mapOffset.Clear();
                mapSize.Clear();
                string[] lines = System.IO.File.ReadAllLines(FilePath);
                int count = 0;
                int Offset = 0;
                System.Console.WriteLine("No of Lines :" + lines.Length);
                foreach (string line in lines)
                {
                    count++;
                    if (count < StartRow)
                        continue;

                    String ClmName = line.Substring(0, 20).Trim();
                    String size = line.Substring(32, 2);
                    int iSize = 0;
                    try
                    {
                        iSize = Int16.Parse(size);

                    }
                    catch (Exception ee)
                    {
                        continue;
                    }
                    mapSize.Add(ClmName, iSize);
                    mapOffset.Add(ClmName, Offset);

                    Console.WriteLine(ClmName + " " + iSize + " " + Offset);
                    Offset = iSize + Offset;


                }
                LineWidth = Offset;

                System.Console.WriteLine("No of ele :" + mapOffset.Count() + "   " + count);
            }
            catch (Exception fileEx)
            {
                MessageBox.Show(fileEx.Message);
            }

        }

        List<String> SymbolList = new List<String>();

        public void ReadTradeFile()
        {
            try
            {
 
                List<String> ExecIdCol = DailyTransactionsServices.GetExecIDCol(TrDate.Value.Date);
                List<String> ClientsList = ClientService.GetClientCodeCollection();
                SymbolList.Clear();
                SymbolList = SecurityServices.GetSecSymbolList();

                string[] lines = System.IO.File.ReadAllLines(AtsDataTxtBox.Text);
                int count = 0;
                int AddedCount = 0;
                int DuplicatedCount = 0;

                progressBar1.Value = 0;
                progressBar1.Maximum = lines.Length;

                System.Console.WriteLine("No of Lines :" + lines.Length);

                String[] TaxsFees = null;
                try
                {
                    TaxsFees = ConfigurationSettings.AppSettings.AllKeys;
                }
                catch (Exception er)
                {
                    MessageBox.Show("Error in App.config file.");
                    return;
                }

                if (TaxsFees.Length == 0)
                {
                    MessageBox.Show("Error in reading config file.", "Error");
                    return;
                }

                if (lines.Length <= 1)
                {
                    MessageBox.Show("No data available", "Message");
                    return;
                }
                DateTime SettlementDate = DateTime.MinValue;

                foreach (string line in lines)
                {
                    //////////////////////////////////////////////////////////////////////////////////////////////////
                    count++;
                    if(count == 1)
                    {
                        String[] MetaData = line.Split('|');
                        if (MetaData.Length != 4)
                        {
                            MessageBox.Show("Invalid Data file. Code : 0001", "Error");
                            return;
                        }

                        if (MetaData[2] != "trades")
                        {
                            MessageBox.Show("Invalid Data file type.", "Error");
                            return;
                        }
                        if (MetaData[1] != AgentCode)
                        {
                            MessageBox.Show("Data file does not match with agent.", "Error");
                            return;
                        }
                        
                        if (MetaData[3].Trim() != "" )
                        {
                            SettlementDate = DateTime.Parse(MetaData[3].Trim());
                        }
                        else
                        {
                            MessageBox.Show("Invalid Data file. Code : 0002", "Error");
                            return;
                        }
                        //count++;
                        progressBar1.Increment(1);
                        continue;

                    }

                    
                    //////////////////////////////////////////////////////////////////////////////////////////////////
                    
                    
                    
                    //Checking the length of a line
                    if (line.Length != LineWidth)
                    {
                        MessageBox.Show("Error in Line " + count + " of the ats2_ttr data file.\n" +
                                       "Please check the file and try again.");
                        return;

                    }


                    int Quan = Int32.Parse(GetValue("quantity", line));
                    Double Price = Double.Parse(GetValue("price", line));

                    //Trading date has to be matched with the date in the file.
                    //if (GetValue("trade_date", line).CompareTo(TrDate.Value.ToString("yyyy/MM/dd")) != 0 )
                    //{
                    //    MessageBox.Show("Trading date mismatch");
                    //    return;
                    //}

                    progressBar1.Increment(1);

                    String JointACNo = GetValue("joint_ac_no", line);
                    if (JointACNo.Length == 1)
                        JointACNo = "0" + JointACNo;

                    String ClientCode = GetValue("participant id", line) + "-" +
                                        GetValue("client_prefix", line) + "-" +
                                        GetValue("client_suffix", line) + "-" +
                                        JointACNo;
                    String CompanySymbol = GetValue("company_id", line) + "-" +
                                                                GetValue("main_type", line) + "-" +
                                                                GetValue("sub_type", line);

                    //if symbol was not there in DB, it will be added.
                    UpdateSecurity(CompanySymbol);

                    if (!ClientsList.Contains(ClientCode))
                    {
                        if (GetValue("buy_sell", line) == "S")
                            QuickAddClient(ClientCode, GetValue("broker_id_sell", line));                       
                        else
                            QuickAddClient(ClientCode, GetValue("broker_id_buy", line));    

                        
                        ClientsList.Add(ClientCode);
                        //continue;
                    }

                    String ExecID = GetValue("buy_sell", line) + GetValue("execution_id", line);
                    if (ExecIdCol.Contains(ExecID))
                    {
                        DuplicatedCount++;
                        //LogBox.AppendText("Transaction record already exist.( Exec ID -" + ExecID + " )\n");
                        continue;
                    }
                    else
                    {
                        ExecIdCol.Add(ExecID);
                    }

                    if (GetValue("status", line) != "1") //status should be 1
                    {
                        continue;
                    }



                    Double Amount = Quan * Price;

                    double TotalTax = 0;
                    foreach (String tax in TaxsFees)
                    {
                        TotalTax = TotalTax + Double.Parse(GetValue(tax, line));

                    }
                    if (GetValue("buy_sell", line) == "S")
                    {
                        Amount = Amount - TotalTax;
                        Quan = Quan * -1;
                    }
                    else
                    {
                        Amount = (Amount + TotalTax) * -1;
                    }

                    try
                    {
                        Updateportfolio(ClientCode, CompanySymbol, Quan);

                        //LogBox.AppendText(ClientCode + " : " + Amount + "\n");
                        DailyTransactions DailyTr = new DailyTransactions();


                        DailyTr.TradeDate = DateTime.Parse(GetValue("trade_date", line) + " " + GetValue("trade_time", line));

                        DailyTr.TranId = GetValue("tran_id", line);
                        DailyTr.ExecutionId = ExecID;
                        DailyTr.BuySell = GetValue("buy_sell", line);
                        DailyTr.CompanySymbol = CompanySymbol;
                        //DailyTr.Quantity            = Int32.Parse(GetValue("quantity", line));
                        DailyTr.Quantity = Int32.Parse(GetValue("quantity", line));
                        DailyTr.Price = double.Parse(GetValue("price", line));
                        DailyTr.TaxFlag = Int32.Parse(GetValue("tax_flag", line));
                        DailyTr.BrokerIdBuy = GetValue("broker_id_buy", line);
                        DailyTr.BrokerIdSell = GetValue("broker_id_sell", line);
                        DailyTr.BuyingContractNo = Int32.Parse(GetValue("buying_contract_no", line));
                        DailyTr.SellingContractNo = Int32.Parse(GetValue("selling_contract_no", line));
                        DailyTr.ClientCode = ClientCode;
                        DailyTr.ParticipantId = GetValue("participant id", line);
                        DailyTr.ForeignFlag = Int32.Parse(GetValue("foreign_flag", line));
                        DailyTr.Amount = Amount;
                        DailyTr.OrderId = GetValue("order_id", line);
                        DailyTr.Status = Int32.Parse(GetValue("status", line));
                        DailyTr.SettleDate = SettlementDate;

                        DailyTransactionsServices.Add(DailyTr);
                        AddedCount++;
                    }
                    catch (System.Data.OracleClient.OracleException Ora)
                    {
                        if (Ora.Code == 1)
                        {
                            DuplicatedCount++;
                            //LogBox.AppendText("Transaction record already exist.( Exec ID -" + GetValue("execution_id", line) + " )\n");
                        }
                        else
                            MessageBox.Show(Ora.Message, "Error!");

                    }

                    //writing to the DB                   


                }
                if (DuplicatedCount != 0)
                {
                    LogBox.AppendText(DuplicatedCount + " records were already existed.\n");
                }
                LogBox.AppendText(AddedCount + " records were added to the database.\n");

                CDSTran trans = new CDSTran(); //To track processing is done
                trans.transaction_date = TrDate.Value.Date;
                trans.reference = "Trades";
                CDSTranServices.Add(trans);

                //System.Console.WriteLine("No of records :" + count);


            }
            catch (Exception fileEx)
            {
                //throw;
                MessageBox.Show(fileEx.Message, "Error");
            }
        }



        private void QuickAddClient(String ClientCode, String BrockerCode)
        {
            try
            {
                Client NewClient = new Client();

                NewClient.Code = ClientCode;
                NewClient.Broker = BrockerCode;
                NewClient.RegDate = DateTime.Now.Date;
                NewClient.Advisor = "GEN";

                ClientService.Add(NewClient);
                //CDSTranServices.Add(trans);

            }
            catch (System.Data.OracleClient.OracleException Ora)
            {
                if (Ora.Code == 1)
                    LogBox.AppendText("Client already exist.( Client Code -" + ClientCode + " )\n");
                else
                    MessageBox.Show(Ora.Message, "Error!");

            }

        }



       static String GetValue(String ClmName, String Line)
       {
           String value = "";
           value = Line.Substring(mapOffset[ClmName], mapSize[ClmName]);
           return value.Trim();
       }

       
       private void UpdateSecurity(String CompanySymbol)
       {
           //Security SecObj = SecurityServices.GetSecurityBySymbol(CompanySymbol);

           if (!SymbolList.Contains(CompanySymbol))
           {
               try
               {
                   Security SecObj = new Security();
                   SecObj.Name = CompanySymbol;
                   SecObj.Symbol = CompanySymbol;
                   SecObj.MarketValue = 0;
                   SecObj.MarginPercentage = 100;
                   SecurityServices.Add(SecObj);

               }
               catch (System.Exception ex)
               {
                   MessageBox.Show("Database Error", "Error");
                   return;
               }

               SymbolList.Add(CompanySymbol);
           }

       }



       private void Updateportfolio(String ClientCode, String CompanySymbol, int Quantity)
       {
           Portfolio ClPort = PortfolioServices.GetPortfolioByCodeAndSymbol(ClientCode, CompanySymbol);

           if (ClPort == null)
           {
               ClPort = new Portfolio();
               ClPort.Code = ClientCode;
               ClPort.Symbol = CompanySymbol;
               ClPort.Quantity = Quantity + ClPort.Quantity;

               PortfolioServices.Add(ClPort);
           }
           else
           {
               ClPort.Quantity = ClPort.Quantity + Quantity;
               if (ClPort.Quantity == 0)
               {
                   PortfolioServices.Delete(ClientCode, CompanySymbol);
               }
               else
               {
                   PortfolioServices.Update(ClPort);
               }

           }

       }

       private void button1_Click(object sender, EventArgs e)
       {
           if (!PreValidation())
               return;

           ReadTradeHdrFile(CDSTranHdrFile, 3);
           ReadCDSTranDataFile();
           progressBar1.Value = 0;
       }


       DateTime TradeDate = DateTime.MinValue;

       public void ReadCDSTranDataFile()
       {
           
           int AddedCount = 0;
           try
           {
               List<String> ClientsList = ClientService.GetClientCodeCollection();
               List<String> CDSTable = CDSTranServices.GetCDSTranCollectionDataTable(TrDate.Value.Date);

               string[] lines = System.IO.File.ReadAllLines(PortFile.Text);

               CultureInfo provider = CultureInfo.InvariantCulture;
               progressBar1.Value = 0;
               progressBar1.Maximum = lines.Length;
               

               SymbolList.Clear();
               SymbolList = SecurityServices.GetSecSymbolList();

               String line = "";
               for (int count = 1; count <= lines.Length; count++)
               {
                   line = lines[count-1];
                   //System.Console.WriteLine("No of Lines :" + line.Length);
                   
                   //////////////////////////////////////////////////////////////////////////////////////////////////
                   if (count == 1)
                   {

                       String[] MetaData = line.Split('|');
                       if (MetaData.Length != 5)
                       {
                           MessageBox.Show("Invalid Data file.", "Error");
                           return;
                       }

                       if (MetaData[2] != "CDSTran")
                       {
                           MessageBox.Show("Invalid Data file type.", "Error");
                           return;
                       }
                       if (MetaData[1] != AgentCode)
                       {
                           MessageBox.Show("Data file does not match with MT company.", "Error");
                           return;
                       }

                       if (MetaData[3].Trim() != "")
                       {
                           TradeDate = DateTime.Parse(MetaData[3].Trim());
                       }
                       else
                       {
                           MessageBox.Show("Invalid Data file.", "Error");
                           return;
                       }
                       if (MetaData[4].Trim() != "")
                       {
                           BROKER_CODE = MetaData[4].Trim();
                       }
                       else
                       {
                           MessageBox.Show("Invalid Data file.", "Error");
                           return;
                       }

                       if (TradeDate != TrDate.Value.Date)
                       {
                           MessageBox.Show("Date mismatch. Please check the trade date and the Data file.", "Message");
                           return;
                       }
                       //count++;
                       progressBar1.Increment(1);
                       continue;

                   }

                   //////////////////////////////////////////////////////////////////////////////////////////////////

                   if (line[0] == '#')
                   {
                       count = ProcessClientTransferData(count, lines) + 1;
                       if (count < lines.Length)
                       {
                           line = lines[count];
                           count++;
                       }
                       else
                           break;
                       //break;
                   }


                   //Checking the length of a line
                   if (line.Length != LineWidth)
                   {
                       MessageBox.Show("Error in Line " + count + " of the CDS_Tran data file.\n" +
                                      "Please check the file and try again.");
                       return;

                   }

                   //Trading date has to be matched with the date in the file.
                   if (GetValue("transaction_date", line).CompareTo(TrDate.Value.ToString("ddMMyyyy")) != 0)
                   {
                       MessageBox.Show("Trading date mismatch", "Error");
                       return;
                   }

                   progressBar1.Increment(1);

                   String JointACNo = GetValue("joint_ac_no", line);
                   if (JointACNo.Length == 1)
                       JointACNo = "0" + JointACNo;

                   String ClientCode = BROKER_CODE + "-" +
                                       GetValue("client_prefix", line) + "-" +
                                       GetValue("client_suffix", line) + "-" +
                                       JointACNo;
                   int Quan = 0;


                   if (int.Parse(GetValue("quantity", line)) < 0)
                   {
                       Quan = Quan * -1;

                   }

                   //Console.WriteLine(ClientCode);
                   if (!ClientsList.Contains(ClientCode))
                   {
                       //continue;
                   }

                   if (CDSTable.Contains(GetValue("reference", line)))
                   {
                       continue;
                   }


                   String CompanySymbol = GetValue("company_id", line) + "-" +
                                           GetValue("main_type", line) + "-" +
                                           GetValue("sub_type", line);

                   UpdateSecurity(CompanySymbol);

                   try
                   {

                       String ExecId = "P" + GetValue("reference", line);

                       DateTime TranDate = DateTime.ParseExact(GetValue("transaction_date", line), "ddMMyyyy", provider);

                       DailyTransactions DTransac =
                           DailyTransactionsServices.GetDailyTransactionsByExecIdAndDate(ExecId, TranDate);

                       if (DTransac != null)
                       {
                           LogBox.AppendText("Transaction record already exist. Line No." + count + "\n");
                           continue;
                       }
                       Updateportfolio(ClientCode, CompanySymbol, Int32.Parse(GetValue("quantity", line)));

                       CDSTran trans = new CDSTran();

                       trans.transaction_date = TranDate;
                       trans.reference = GetValue("reference", line);
                       trans.company_symbol = CompanySymbol;
                       trans.client_code = ClientCode;
                       trans.transaction_type = GetValue("transaction_type", line);
                       trans.transaction_desc = GetValue("transaction_desc", line);
                       trans.quantity = Int32.Parse(GetValue("quantity", line));
                       trans.trade_date = GetValue("trade_date", line);
                       trans.broker_code = BROKER_CODE;

                       CDSTranServices.Add(trans);

                       AddedCount++;
                   }
                   catch (System.Data.OracleClient.OracleException Ora)
                   {
                       if (Ora.Code == 1)
                           LogBox.AppendText("Transaction record already exist.( Exec ID -" + GetValue("execution_id", line) + " )\n");
                       else
                           MessageBox.Show(Ora.Message, "Error!");

                   }

                   //LogBox.AppendText(ClientCode + "\n");
               }
               LogBox.AppendText("New records were added to the database.\n");
               
               CDSTran trans1 = new CDSTran(); //To track processing is done
               trans1.transaction_date = TrDate.Value.Date;
               trans1.reference = "CDSTran";
               CDSTranServices.Add(trans1);

           }
           catch (Exception fileEx)
           {
               MessageBox.Show(fileEx.Message);
           }

       }



        int ProcessClientTransferData(int count, String[] lines)
        {

            LogBox.AppendText("- - - Adding new clients to the database. - - -\n");//count--;
            String line = lines[count];
            //new clients
            while (line[0] != '#')
            {
                String[] ClientValues = line.Split('|');
                Client NewClient = new Client();
                try
                {
                    UpdateAdvisor(ClientValues[11]);
                    UpdateBroker(ClientValues[9]);

                    NewClient.Code = ClientValues[0];
                    NewClient.Title = ClientValues[1];
                    NewClient.Initials = ClientValues[2]; 
                    NewClient.OtherNames = ClientValues[3];
                    NewClient.Surname = ClientValues[4];
                    NewClient.Address_1 = ClientValues[5];
                    NewClient.Address_2 = ClientValues[6];
                    NewClient.Address_3 = ClientValues[7];
                    NewClient.Address_4 = ClientValues[8];
                    NewClient.Broker = ClientValues[9];
                    NewClient.Agent = ClientValues[10];
                    NewClient.Advisor = ClientValues[11];
                    DateTime RegDate = DateTime.MinValue;
                    if (DateTime.TryParse(ClientValues[12], out RegDate))
                        NewClient.RegDate = RegDate;                   
                    DateTime MTRegDate = DateTime.MinValue;
                    if (DateTime.TryParse(ClientValues[13], out MTRegDate))
                        NewClient.MTRegDate = MTRegDate;
                    NewClient.MarginClient = 1;
                    NewClient.Telephone1 = ClientValues[14];
                    NewClient.Telephone2 = ClientValues[15];
                    NewClient.Fax = ClientValues[16];
                    NewClient.InterestRate = double.Parse(ClientValues[17]);
                    NewClient.MarginLimit = double.Parse(ClientValues[18]);





                    ClientService.Add(NewClient);

                    

                   // AddedCount++;
                }
                catch (System.Data.OracleClient.OracleException Ora)
                {
                    if (Ora.Code == 1)
                    {
                        LogBox.AppendText("Client already exist.( Client Code -" + ClientValues[0] + " )\n");
                        ClientService.Update(NewClient);
                    }
                    else
                        MessageBox.Show(Ora.Message, "Error!");

                }

                
                //LogBox.AppendText(line+"\n");
                progressBar1.Increment(1);
                count++;
                line = lines[count];
            }
            LogBox.AppendText("- - - Adding new clients to the database - Done. - - -\n");//count--;
            


            //new clients' portfolios
            LogBox.AppendText("- - - Adding new clients portfolios to the database. - - -\n");//count--;
            count++;
            line = lines[count];            
            while (line[0] != '#')
            {

                String[] PortValues = line.Split('|');
                try
                {
                    UpdateSecurity(PortValues[1]);
                    Portfolio NewPortfolio = new Portfolio();

                    NewPortfolio.Code = PortValues[0];
                    NewPortfolio.Symbol = PortValues[1];
                    NewPortfolio.Quantity = Int32.Parse(PortValues[2]);

                    PortfolioServices.Add(NewPortfolio);

                    // AddedCount++;
                }
                catch (System.Data.OracleClient.OracleException Ora)
                {
                    if (Ora.Code == 1)
                        LogBox.AppendText("Portfolio record already exist.( Client Code - " + PortValues[0] +
                           " , Symbol - " + PortValues[1] + ").\n");
                    else
                        MessageBox.Show(Ora.Message, "Error!");

                }


                //LogBox.AppendText(line + "\n");
                progressBar1.Increment(1);
                count++;
                line = lines[count];
            }
            LogBox.AppendText("- - - Adding new clients portfolios to the database - Done. - - -\n");//count--;


            //New clients' account balances.
            LogBox.AppendText("- - - Adding new clients account balances to the database. - - -\n");//count--;
            count++;
            line = lines[count];            
            while (line[0] != '#')
            {

                String[] AccValues = line.Split('|');
                
                /*
                try
                {
                    LoanAccount NewAcc = new LoanAccount();

                    double AccBalance = 0.0f;
                    if (double.TryParse(AccValues[1], out AccBalance))
                    {
                        if (AccBalance >= 0.0f)
                            NewAcc.Amount = AccBalance;

                    }

                    NewAcc.ClientCode = AccValues[0];
                    NewAcc.EntryType = "PA";
                    NewAcc.CreatedDate = TradeDate.Date;
                    NewAcc.Remarks = "Initial payment";
                    NewAcc.TrParticulars = "Initial payment";
                    NewAcc.ReferenceNo = "IP-" + DateTime.Now.ToString("yyyyMMddHHmmss") + "-" + count;

                    LoanAccountServices.Add(NewAcc);

                    // AddedCount++;
                }
                catch (System.Data.OracleClient.OracleException Ora)
                {
                    if (Ora.Code == 1)
                        LogBox.AppendText("Account balance already exist.( Client Code - " + AccValues[0] + ").\n");
                    else
                        MessageBox.Show(Ora.Message, "Error!");

                }
                
                */

                try
                {

                    //InitialSettlement IniSettle = InitialSettlementServices.GetInitialSettlementByClientCode(AccValues[0]);
                    //if (double.Parse(AccValues[1]) < 0)
                    //{
                    //    if (IniSettle == null)
                    //    {
                    //        IniSettle = new InitialSettlement();
                    //        IniSettle.ClientCode = AccValues[0];
                    //        IniSettle.Amount = double.Parse(AccValues[1]) * -1;
                    //        IniSettle.AddedDate = DateTime.Now;
                    //        IniSettle.SentToBroker = 0;
                    //        IniSettle.AccPosted = 0;
                    //        IniSettle.SettledAmount = 0;

                    //        InitialSettlementServices.Add(IniSettle);
                    //    }
                    //    else
                    //    {
                    //        throw new Exception("Record already exist.");
                    //    }
                    //}
 
                    DailyTransactionsServices.AddInitialAccBal(AccValues[0], double.Parse(AccValues[1]), true);

                    
                }
                catch (System.Exception ex)
                {
                    MessageBox.Show("Failed to add initial account balance\nError: " + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }


                //LogBox.AppendText(line + "\n");
                progressBar1.Increment(1);
                count++;
                if (lines.Length == count)
                    break;
                line = lines[count];
            }
            progressBar1.Increment(3);
            return count;


        }

        private void TrDate_ValueChanged(object sender, EventArgs e)
        {

        }

        void ReadTrsumFile()
        {
            try
            {

                string[] lines = System.IO.File.ReadAllLines(TrsumFile.Text);
                int count = 0;
                int AddedCount = 0;

                progressBar1.Value = 0;
                progressBar1.Maximum = lines.Length;

                String TempComSymbol = "";
                String description = "";
                Double Price = 0.0;
                String CompanySymbol = "";

                bool IsEnd = false;

                Double ClosingPrice = 0.0;
                foreach (string line in lines)
                {
                    count++;
                    //Checking the length of a line
                    if (line.Length != LineWidth)
                    {
                        // MessageBox.Show("Error in Line " + count + " of the ats2_ttr data file.\n" +
                        //               "Please check the file and try again.");
                        if (GetValue("description", line) == "... SPECIAL LOTS ...")
                        {
                            IsEnd = true;
                        }
                        else
                        {
                            LogBox.AppendText("Length mismatch in line No." + count + " of the trsum file.\n");
                            continue;
                        }


                    }

                    if (!IsEnd)
                    {

                        Price = Double.Parse(GetValue("price1", line) + "." + GetValue("price2", line));

                        //Trading date has to be matched with the date in the file.
                        if (GetValue("trade_date", line).CompareTo(TrDate.Value.ToString("yyyyMMdd")) != 0)
                        {
                            MessageBox.Show("Trading date mismatch");
                            return;
                        }

                        progressBar1.Increment(1);
                        CompanySymbol = GetValue("company_id", line) + "-" +
                                                                    GetValue("main_type", line) + "-" +
                                                                    GetValue("sub_type", line);

                    }
                    else
                    {
                        CompanySymbol = "End";
                    }
                    //UpdateSecurity(CompanySymbol);//////////////////////////////

                    if (TempComSymbol == "")
                    {
                        TempComSymbol = CompanySymbol;

                    }


                    if (CompanySymbol == TempComSymbol)
                    {
                        ClosingPrice = Price;
                        description = GetValue("description", line);

                    }
                    else
                    {
                        Security Share = SecurityServices.GetSecurityBySymbol(TempComSymbol);
                        Double MktVal = ClosingPrice;
                        if (Share == null)
                        {
                            Share = new Security();
                            Share.Symbol = TempComSymbol;
                            Share.Name = description;
                            Share.MarketValue = double.Parse(MktVal.ToString());
                            Share.MarginPercentage = 100;
                            SecurityServices.Add(Share);

                        }
                        else
                        {
                        
                            Share.Name = description;                            
                            Share.MarketValue = double.Parse(MktVal.ToString());

                            SecurityServices.Update(Share);

                        }
                        if (IsEnd)
                            break;

                        //MessageBox.Show(" " + TempComSymbol + " : " + TotalTurnover/TotalQuantity);

                        TempComSymbol = CompanySymbol;
                        ClosingPrice = Price;
                        description = GetValue("description", line);
                    }


                }
                LogBox.AppendText("Market summary update done !\n");
                //System.Console.WriteLine("No of records :" + count);


            }
            catch (Exception fileEx)
            {
                //throw;
                MessageBox.Show(fileEx.Message, "Error");
            }
        }



        private void UpdateAdvisor(String AdvisorCode)
        {
            Advisor NwAdvisor = AdvisorServices.GetAdvisorByCode(AdvisorCode);

            if (NwAdvisor == null)
            {
                NwAdvisor = new Advisor();
                NwAdvisor.Code = AdvisorCode;
                NwAdvisor.Name = AdvisorCode;
                NwAdvisor.CreatedDate = DateTime.Now.Date;

                AdvisorServices.Add(NwAdvisor);
            }

        }

        private void UpdateBroker(String BrokerCode)
        {
            Broker NwBroker = BrokerServices.GetBrokerByCode(BrokerCode);

            if (NwBroker == null)
            {
                NwBroker = new Broker();
                NwBroker.Code = BrokerCode;
                NwBroker.Name = BrokerCode;
                NwBroker.CreatedDate = DateTime.Now.Date;
            

                BrokerServices.Add(NwBroker);
            }

        }





       
        //////////////////////////////////////////////////////////////////////////////

    }


}
